package com.qf.driver.mqtt.handler;

import com.qf.common.sdk.bean.MessageHeader;
import com.qf.common.sdk.bean.MessagePayload;
import com.qf.common.sdk.bean.MessageType;
import com.qf.common.sdk.bean.MqttMessage;
import com.qf.driver.service.MqttReciveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;

/**
 * 接收硬件设备上报的数据, 从emqx服务器中使用mqtt协议接收
 * @author 千锋健哥
 */
@Slf4j
@Configuration
public class MqttReciveHandler {

    @Autowired
    private MqttReciveService mqttReciveService;

    /**
     * 接收emqx服务器中的消息并处理
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handlerRevice() {
        return message -> {
            if (message != null) {
                log.info("设备发送过来的数据内容是:" + message.getPayload().toString());
                log.info("设备发送过来的数据消息体是:" + message.getHeaders().toString());
                //构造消息体对象
                MessagePayload messagePayload = new MessagePayload(message.getPayload().toString(), MessageType.MQTT);
                //构造消息头对象
                MessageHeader messageHeader = new MessageHeader(message.getHeaders());
                //将消息头和消息体封装成消息对象
                MqttMessage mqttMessage = new MqttMessage(messageHeader, messagePayload);

                mqttReciveService.reciveMessage(mqttMessage);
            }
        };
    }
}
